import turtle
import math
from draw_defs import draw_circle, draw_board
import game_defs
from game_loop import game_loop

canvas = turtle.Screen()
pen = turtle.Turtle()
step_len = 50

def main_paint():
    draw_board(pen, step_len, -0.5)
    draw_board(pen, step_len, 0.5)

def board_txt2graph(x, y, bd):
    num_rows = len(bd)
    num_cols = len(bd[0])

    pen.penup()
    start_x = x - (num_cols // 2) * (step_len/2)
    start_y = y + (num_rows // 2) * (step_len/2)
    pen.goto(start_x, start_y)
    pen.pendown()

    for row in range(num_rows):
        for col in range(num_cols):
            if bd[row][col] == 'X':
                draw_circle(pen, start_x + col * step_len/2, start_y - row * step_len/2, 1, step_len/5)
            elif bd[row][col] == 'O':
                draw_circle(pen, start_x + col * step_len/2, start_y - row * step_len/2, 0, step_len/5)
            # elif bd[row][col] != '@':
            #    print("非法棋子:", row, ',', col, ',', bd[row][col]  )

def main():
    game_defs.print_board()
    # TODO: 判断游戏是否结束，输出胜负结果并结束循环

    main_paint()
    board_txt2graph( -2*step_len, 0, game_defs.board)
    board_txt2graph( 2*step_len, 0, game_defs.board2)
    pen.hideturtle()  # 隐藏画笔
    
    while True:
        try:
            # 启动游戏
            game_loop()

            game_defs.print_board()
            # TODO: 判断游戏是否结束，输出胜负结果并结束循环
            canvas.clear()
            pen.showturtle()  # 显示画笔
            main_paint()
            board_txt2graph( -2*step_len, 0, game_defs.board)
            board_txt2graph( 2*step_len, 0, game_defs.board2)
            pen.hideturtle()  # 隐藏画笔
            
        except ValueError as e:
            print(str(e))
            continue

    canvas.exitonclick()

if __name__ == '__main__':
    main()
